<template lang="pug">
  .page
    .AccountsReceivableManage
      .search-form.mb-10.pl-10.pr-10
        Form.ivu-row.ivu-form-basic(ref="formData" :model="formData" :rules="rules" :label-width="90")
          FormItem.form-item.ivu-col.pr-20.mb-15(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
            template(v-if="item.type === 'select'")
              Select(v-model="formData[item.model]" :placeholder="item.placeholder" clearable)
                Option(
                  v-for="(c_item, index) in arrListDown[item.options]"
                  :value="c_item.value"
                  :key="index"
                ) {{ c_item.label }}
            template(v-if="item.type === 'input'")
              Input(v-model="formData[item.model]" :placeholder="item.placeholder" clearable)
            template(v-if="item.type === 'radio'")
              RadioGroup(type="button" v-model="formData[item.model]")
                Radio.display-inline-block(v-for="(c_item,idx) of item.radioArr" :label="c_item.value" :key="idx") {{c_item.label}}
            template(v-if="item.type === 'interval'")
              DatePicker.pull-left.interval(v-model="formData[item.model1]" :placeholder="item.placeholder1" type="month" @on-change="handleChangeDatePicker")
              span.pl-10.pr-10.pull-left.line-h-32 --
              DatePicker.pull-left.interval(v-model="formData[item.model2]" :placeholder="item.placeholder2" type="month" @on-change="handleChangeDatePicker")
            template(v-if="item.type === 'button'")
              Button(v-if="hasFind" type="info" @click="searchFn") 查询

      .pl-20.pr-20.bg-white
        Table.beautiful-table(:columns="thead" :data="tableData" :stripe="true" ref="demoTable"
          @on-selection-change="handleOnSelectChange"
        )
          .clearfix.pr-24.pl-12.overflow-hidden(slot="header")
            .table-title-lefttxt.pull-left
              a.text-info(@click="backInitTable") 根目录
              Icon.ml-5.mr-5(type="ios-arrow-forward" v-if="currentFolder.length > 0")
              .display-inline-block.line-h-47(v-for="(folder, folderIndex) of currentFolder")
                a.text-info(v-if="folderIndex !== currentFolder.length - 1" @click="handleChangeFolder(folderIndex, folder.parentId, folder.fileName)") {{folder.fileName}}
                Icon.ml-5.mr-5(type="ios-arrow-forward" v-if="folderIndex !== currentFolder.length - 1")
                span(v-else @click="handleChangeFolder(folderIndex, folder.parentId, folder.fileName)") {{folder.fileName}}
              //- Button(type="text" v-for="(folder, folderIndex) of currentFolder" @click="handleChangeFolder(folderIndex, folder.parentId, folder.fileName)" :disabled="folderIndex === currentFolder.length - 1") {{folder.fileName}}
            .pull-right.table-title-btns
              Button.mr-10(v-if="hasFileUpload" type="info" @click="handleShowImportModal" :disabled="!selectedEmployeeId || selectedEmployeeId.length > 1") 文件上传
              //- Upload.display-inline-block.mr-10(:before-upload="handleBeforeUpload" ref="upload" :show-upload-list="false" :action="'/api/PolicySupport/FileUpload?path='" :on-success="handleImportSuccess")
              //-   Button(type="info" size="small") 文件上传(当前页面)
              Poptip.mr-10(
                v-if="hasDeletePolicySupport"
                confirm
                title="是否删除所选择的政策文件"
                @on-ok="handleSureDelete"
                width="200"
              )
                Button(type="warning" size="small" :disabled="!selectedEmployeeId.length > 0") 删除
              Button.mr-10(type="info" size="small" @click="handleShowCreateFileModal" :disabled="!selectedEmployeeId || selectedEmployeeId.length > 1") 新建文件夹
              Button.mr-10(v-if="hasFileShare" type="info" size="small" :disabled="!selectedEmployeeId.length > 0" @click="handleShowOrganizationUnitTreeModal") 文件共享
              //- Button.mr-10(type="warning" size="small" :disabled="!selectedEmployeeId.length > 0" @click="unFileShare") 取消共享
              Poptip(
                v-if="hasUnFileShare"
                confirm
                title="是否取消共享"
                @on-ok="unFileShare"
                width="200"
              )
                Button(type="warning" size="small" :disabled="!selectedEmployeeId.length > 0") 取消共享
          template(slot-scope="{ row, index }" slot="action")
            Button.mr-10(v-if="hasReName" type="text" size="small" @click="handleShowReNameModal(row.id)") 重命名
            //- Poptip(
            //-   confirm
            //-   title="请输入新文件名称"
            //-   @on-ok="reName(row.id)"
            //-   width="200"
            //- )
            //-   Input(type="text" v-model="currentNewName")
            //-   Button(type="warning" size="small") 重命名
            //- Upload.display-inline-block.mr-10(:before-upload="handleBeforeUpload" ref="upload" :show-upload-list="false" :action="'/api/PolicySupport/FileUpload?path=' + row.path" :on-success="handleImportSuccess")
            //-   Button(type="info" size="small") 文件上传
            //- Button(v-if="hasDownloadFile" :to="row.downLoadUrl" type="info" target="_blank" size="small") 下载
            Button.mr-10(v-if="hasDownloadFile" type="info" size="small" @click="handleDownloadFile(row.id)") 下载
            Button(type="info" size="small" @click="handleShowEmailNoticeModal") 邮件提醒(待)
          .clearfix.pl-20.pr-20(slot="footer")
            Page(
              :total="tableComone.totalRows"
              @on-change="onChangePage"
              @on-page-size-change="onpageSizeChange"
              show-sizer
              show-total
              placement="top"
              prev-text="上一页"
              next-text="下一页"
              :page-size-opts="[10, 20, 30, 50, 100]"
            )

    //- 新建文件夹弹窗
    CreateFileModal(ref="CreateFileModal" @query="searchFn" :PSID="PSID")

    //- 组织架构树
    OrganizationUnitTreeModal(ref="OrganizationUnitTreeModal" @handleSubmit="fileShare")

    //- 组织架构树
    ReNameModal(ref="ReNameModal" @handleSubmit="reName")

    //- 批量导入弹窗
    ImportModal(ref="ImportModal" @query="searchFn" :PSID="PSID")

    //- 发送邮件提醒弹窗
    EmailNoticeModal(ref="EmailNoticeModal" @query="searchFn")
</template>

<script>
import { Common } from '@/utils/common.js'
import { PolicySupportApi } from '@/api/PolicySupport.api.js'
import { EnumApi } from '@/api/Enum.api.js'
import { PolicySupportThead } from './PStableHead.js'
import _cloneDeep from 'clone-deep'
import { EmployeesApi } from '@/api/Employees.api.js'
import CreateFileModal from './modal/createFileModal.vue'
import OrganizationUnitTreeModal from './modal/organizationUnitTreeModal.vue'
import ReNameModal from './modal/reNameModal.vue'
import ImportModal from './modal/importModal.vue'
import EmailNoticeModal from './modal/emailNoticeModal.vue'
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro.replace('/api', '/')

export default {
  name: '',

  components: {
    CreateFileModal,
    OrganizationUnitTreeModal,
    ReNameModal,
    ImportModal,
    EmailNoticeModal
  },

  data () {
    return {
      companyId: '', // 公司ID
      companyName: '', // 公司名称
      employeeId: '', // 员工ID
      // thead: _cloneDeep(PolicySupportThead),
      thead: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '文件名称',
          key: 'fileName',
          render: (h, params) => {
            const text = params.row.fileName
            return h('div', {
              style: {
                cursor: params.row.type === 2 ? 'pointer' : 'default',
                color: params.row.type === 2 ? '#188cc7' : ''
              },
              on: {
                click: () => {
                  params.row.type === 2 ? this.handleFolder(params.index, params) : ''
                }
              }
            }, [
              h('Icon', {
                props: {
                  type: params.row.type === 2 ? 'ios-folder-open' : ''
                },
                style: {
                  color: '#ffb340',
                  marginRight: '5px',
                  fontSize: '24px'
                }
              }),
              h('span', text)
            ])
          }
        },
        {
          title: '文件大小',
          key: 'fileSize'
        },
        {
          title: '上传时间',
          key: 'createrTime',
          render: (h, params) => {
            // const text = (params.row.createrTime).slice(0, 10)
            const text = params.row.createrTime ? params.row.createrTime.substr(0, 10) : ''
            return h('span', text)
          }
        },
        {
          title: '文件类型',
          key: 'fileType',
          render: (h, params) => {
            const text = params.row.fileType === 1 ? '公共文件' : '个人文件'
            return h('span', text)
          }
        },
        {
          title: '创建人',
          key: 'createrName'
        },
        {
          title: '操作',
          key: 'action',
          slot: 'action',
          width: 300
        }
      ],
      initTableData: [],
      tableData: [],
      formData: {
        fileName: '',
        createrName: '',
        createTimeS: '',
        createTimeE: '',
        fileType: ''
      },
      formItem: [
        { type: 'input', label: '文件名称：', placeholder: '请输入文件名称', prop: 'fileName', model: 'fileName', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-8' },
        { type: 'input', label: '创建人：', placeholder: '请输入创建人', prop: 'createrName', model: 'createrName', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-8' },
        { type: 'interval', label: '上传日期：', placeholder1: '开始日期', prop1: 'createTimeS', model1: 'createTimeS', placeholder2: '结束日期', prop2: 'createTimeE', model2: 'createTimeE', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-82' },
        { type: 'select', label: '文件类型：', placeholder: '请选择文件类型', prop: 'fileType', model: 'fileType', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-8', options: 'policysupport' },
        { type: 'button', style: 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-4' }
      ],
      rules: {
        IdCardNo: [
          { type: 'string', message: '请输入正确的身份证号码', pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/ }
        ]
      },
      selectedEmployeeId: [], // 勾选的id集合,array格式
      selectedEmployeeArr: [], // 勾选的id, name数组集合
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10 // 当前页面展示条数
      },
      downLoadRul: '',
      arrListDown: {
        policysupport: []
      },
      file: null,
      currentRow: '',
      currentFolder: [
        // {fileName: '345121', parentId: 'c27810c1decee91180c1509a4c9f0611', type: 2},
        // {fileName: 'test1', parentId: '93b5a1cadfcee91180c1509a4c9f0611', type: 2},
        // {fileName: '哎呀妈呀', parentId: 'f386cea5b6cfe91180c1509a4c9f0611', type: 2}
      ],
      PSID: 'local'
    }
  },

  computed: {
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 下载
    hasDownloadFile () {
      return this.actionArr.indexOf('DownloadFile') > -1
    },
    // 重命名
    hasReName () {
      return this.actionArr.indexOf('ReName') > -1
    },
    // 删除
    hasDeletePolicySupport () {
      return this.actionArr.indexOf('DeletePolicySupport') > -1
    },
    // 文件共享
    hasFileShare () {
      return this.actionArr.indexOf('FileShare') > -1
    },
    // 文件上传
    hasFileUpload () {
      return this.actionArr.indexOf('FileUpload') > -1
    },
    // 查询
    hasFind () {
      return this.actionArr.indexOf('GetPolicySupportList') > -1
    },
    // 取消共享
    hasUnFileShare () {
      return this.actionArr.indexOf('UnFileShare') > -1
    }

  },

  mounted () {
    this.query()
    this.getEnum()
  },

  methods: {
    // 数据字典
    getEnum () {
      let groupName = 'policysupport'
      Common.getEnum2(groupName, this.arrListDown)
      console.log('政策支持 数据字典：', this.arrListDown)
    },

    // 搜索
    searchFn () {
      this.tableComone.pageIndex = 1
      this.query()
    },

    /**
     * 分页页码变动
     * @param {Number} val pageIndex
     */
    onChangePage (val) {
      this.tableComone.pageIndex = val
      this.query()
    },
    /**
     * 分页页码变动
     * @param {Number} val pageSize
     */
    onpageSizeChange (val) {
      this.tableComone.pageIndex = 1
      this.tableComone.pageSize = val
      this.query()
    },
    /**
     * 分页查询接口
     * @param {Object} obj {pageIndex, pageSize}
     */
    async query () {
      var params = {
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize
      }
      let res = await PolicySupportApi.getPolicySupportList({ ...params, ...this.formData })
      console.log('政策支持列表res: ', res)
      if (res.status === 200 && res.data.success) {
        this.initTableData = res.data.data // 初始table数据
        this.tableData = res.data.data
        this.tableComone.totalRows = res.data.totalRows
        this.tableData.map(row => {
          row.downLoadUrl = '/api/PolicySupport/DownloadFile?id=' + row.id
          console.log('row: ', row)
          // var str = row.path.substring(0, row.path.lastIndexOf('\\') + 1)
          // console.log('str: ', str)
          // row.path = str
          // console.log('❌', this.currentFolder)
          if (this.currentFolder.length > 0) {
            var parentId = this.currentFolder[this.currentFolder.length - 1].parentId
            var fileName = this.currentFolder[this.currentFolder.length - 1].fileName
            this.handleChangeFolder(this.currentFolder.length - 1, parentId, fileName)
          }
          this.selectedEmployeeArr = []
          this.selectedEmployeeId = []
        })
      } else {
        this.tableData = []
      }
      this.loading = false
    },

    // 表格选择操作
    handleOnSelectChange (value) {
      this.selectedEmployeeArr = value.map((item) => {
        return { id: item.id, name: item.name }
      })
      this.selectedEmployeeId = value.map((item) => {
        return item.id
      })
      console.log('列表勾选数组1', this.selectedEmployeeArr)
      console.log('列表勾选数组2', this.selectedEmployeeId)
      // this.PSID = this.selectedEmployeeId[0] || 'local'
      if (this.selectedEmployeeId[0]) {
        this.PSID = this.selectedEmployeeId[0]
      } else if (this.currentFolder.length > 0) {
        // this.PSID = this.currentFolder[this.currentFolder.length - 1].parentId
        this.changePSID(this.currentFolder)
      } else {
        this.PSID = 'local'
      }
      console.log('💗💗💗 PSID: ', this.PSID)
    },

    // 日期选择
    handleChangeDatePicker (val) {
      console.log('val: ', val)
      this.formData.salaryMonth = val
      // this.getDayList()
    },

    // 新建文件夹-弹窗显示
    handleShowCreateFileModal () {
      this.$refs.CreateFileModal.isShowCreateFileModal = true
      this.$refs.CreateFileModal.formData.dirname = ''
      // this.$refs.CreateFileModal.PSID = this.currentFolder.length === 0 ? 'local' : this.currentFolder[this.currentFolder.length - 1].parentId
    },

    // 组织架构树-弹窗显示
    handleShowOrganizationUnitTreeModal () {
      this.$refs.OrganizationUnitTreeModal.isShowOrganizationUnitTreeModal = true
      this.$refs.OrganizationUnitTreeModal.getOrganizationUnitTree()
    },

    // 文件上传-上传前文件
    handleBeforeUpload (file) {
      this.file = file
      console.log('file: ', file)
      // return false
    },

    // 文件上传成功(当前页面fn)
    handleImportSuccess (res) {
      console.log('文件上传res: ', res)
      if (res.code === 200 && res.success) {
        this.$Message.success(res.message)
        console.log('importExcel: ', this.importExcel)
        this.query()
      } else {
        this.$Message.error({
          content: res.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 下载
    async handleDownloadFile (id) {
      let res = await PolicySupportApi.downloadFile({ id: id })
      console.log('res: ', res)
      if (res.data.code === 200 && res.data.success) {
        // this.$Message.success(res.data.message)
        console.log('❤ 返回链接: ', baseUrl + res.data.message)
        window.open(baseUrl + res.data.message, '_blank')
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 删除政策-确认删除
    async handleSureDelete () {
      console.log('确认删除', this.selectedEmployeeId)
      // var params = {
      //   ids: this.selectedEmployeeId
      // }
      let res = await PolicySupportApi.deletePolicySupport(this.selectedEmployeeId)
      console.log('res: ', res)
      if (res.data.code === 200 && res.data.success) {
        this.$Message.success(res.data.message)
        this.query()
      } else {
        
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 文件共享
    async fileShare (selectNode) {
      var params = {
        ids: this.selectedEmployeeId,
        userids: selectNode
      }
      console.log('文件共享params: ', params)
      let res = await PolicySupportApi.fileShare(params)
      console.log('res: ', res)
      if (res.data.code === 200 && res.data.success) {
        this.$Message.success(res.data.message)
        this.query()
        this.selectedEmployeeArr = []
        this.selectedEmployeeId = []
      } else {
        
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 取消共享
    async unFileShare () {
      var params = {
        ids: this.selectedEmployeeId
      }
      let res = await PolicySupportApi.unFileShare(params)
      console.log('res: ', res)
      if (res.data.code === 200 && res.data.success) {
        this.$Message.success(res.data.message)
        this.query()
        this.selectedEmployeeArr = []
        this.selectedEmployeeId = []
      } else {
        
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 重命名 - 显示弹窗
    handleShowReNameModal (id) {
      this.$refs.ReNameModal.isShowReNameModal = true
      this.$refs.ReNameModal.currentNewName = ''
      this.currentRow = id
    },

    // 重命名
    async reName (currentNewName) {
      var params = {
        id: this.currentRow,
        newname: currentNewName
      }
      let res = await PolicySupportApi.reName(params)
      console.log('res: ', res)
      if (res.data.code === 200 && res.data.success) {
        this.$Message.success(res.data.message)
        this.query()
        this.selectedEmployeeArr = []
        this.selectedEmployeeId = []
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 文件上传-显示弹窗
    handleShowImportModal () {
      this.$refs.ImportModal.file = null
      this.$refs.ImportModal.errorData.isError = false
      this.$refs.ImportModal.isShowImportModal = true
      // this.$refs.ImportModal.PSID = this.currentFolder.length === 0 ? 'local' : this.currentFolder[this.currentFolder.length - 1].parentId
      console.log('this.$refs.ImportModal.PSID: ', this.$refs.ImportModal.PSID)
    },

    // 回到根目录
    backInitTable () {
      this.tableData = this.initTableData
      this.currentFolder.length = 0
      this.PSID = 'local'
    },

    // 打开文件夹
    handleFolder (index, params) {
      console.log('🌼 index: ' + index)
      console.log('🐟 params.row: ', params.row)
      this.tableData = params.row.childs
      var folderItem = {
        fileName: params.row.fileName,
        parentId: params.row.id,
        type: params.row.type
      }
      this.currentFolder.push(folderItem)
      this.changePSID(this.currentFolder)
    },

    handleChangeFolder (folderIndex, folderId, folderName) {
      console.log('folderIndex: ' + folderIndex + ', folderId: ' + folderId + ', folderName: ' + folderName)
      this.currentFolder.length = folderIndex + 1
      this.getParents(this.initTableData, folderId)
      this.changePSID(this.currentFolder)
    },

    changePSID (currentFolder) {
      this.PSID = currentFolder[currentFolder.length - 1].parentId
      console.log('⭐⭐⭐ PSID: ', this.PSID)
    },

    // 查找父级
    getParents (data, id) {
      for (var i in data) {
        if (data[i].id == id) {
          this.tableData = data[i].childs
          return data[i].childs
        }
        if (data[i].childs) {
          var ro = this.getParents(data[i].childs, id)
          if (ro !== undefined) {
            return ro.concat(data[i].id)
          }
        }
      }
    },

    handleShowEmailNoticeModal () {
      this.$refs.EmailNoticeModal.show()
    }
  } // methods end
}
</script>

<style lang="less" scoped>

</style>
